package com.android.telephonecall.utils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;

import java.lang.reflect.Type;
import java.util.List;

/**
 * json解析工具类
 */
public class JsonUtils {

    public static <T> T tryParseJson(Object json, Class<T> clz) {
        T model = null;
        try {
            Gson gson = new Gson();
            if (json instanceof String) {
                model = gson.fromJson((String) json, clz);
            } else {
                JsonElement je = gson.toJsonTree(json);
                model = gson.fromJson(je, clz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return model;
    }

    public static <T> List<T> tryParseArray(Object json, Type type) {
        List<T> list = null;
        try {
            Gson gson = new Gson();
            if (json instanceof String) {
                list = gson.fromJson((String) json, type);
            } else {
                JsonElement je = gson.toJsonTree(json);
                list = gson.fromJson(je, type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    public static String toJson(Object object) {
        try {
            return new Gson().toJson(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

}
